package com.coocaa.x.app.hall;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.coocaa.x.app.hall.view.widget.TipToast;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LiteHandlerThread;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader2.ErrorCode;
import com.coocaa.x.service.litedownloader2.aidl.DownloadTask;
import com.coocaa.x.service.litedownloader2.aidl.ILiteDownloadServiceListener;
import com.coocaa.x.service.litedownloader2.aidl.ILiteDownloaderService;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.coocaa.x.uipackage.ThemeActivity;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.ui.api.SkyWithBGLoadingView;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by luwei on 15-6-16.
 */
public class HallBaseActivity extends ThemeActivity {
    private SkyWithBGLoadingView loadingView = null;
    private TextView tipsView = null;
    protected static String hallName = "";
    protected SharedPreferences configSharePreference = null;
    protected Timer log = new Timer();
    private static final String START_TIME = "start";
    private static final String END_TIME = "end";
    public static boolean launchApp = false;
    private static final String APP_DURING = "app_during";
    private long appDuring = 0;
    private ILiteDownloaderService downloader = null;
    private static boolean bInitListener = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        configSharePreference = getSharedPreferences("config", 0);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);

        if (!bInitListener) {
            bInitListener = true;
            post(new Runnable() {
                @Override
                public void run() {
                    try {
                        IBinder binder = XServiceManager.getService("com.coocaa.x.service.litedownloader2");
                        downloader = ILiteDownloaderService.Stub.asInterface(binder);
                        XServiceManager.getLitePMService().addInstallListener(installListener);
                        downloader.addListener(downloaderListener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (!bInitListener) {
            bInitListener = true;
            post(new Runnable() {
                @Override
                public void run() {
                    try {
                        IBinder binder = XServiceManager.getService("com.coocaa.x.service.litedownloader2");
                        downloader = ILiteDownloaderService.Stub.asInterface(binder);
                        XServiceManager.getLitePMService().addInstallListener(installListener);
                        downloader.addListener(downloaderListener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        super.onNewIntent(intent);
    }

    public void showLoading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loadingView == null) {
                    loadingView = new SkyWithBGLoadingView(HallBaseActivity.this);
                    loadingView.setLayoutParams(new FrameLayout.LayoutParams(CoocaaApplication.Div(124), CoocaaApplication.Div(124), Gravity.CENTER));
                }
                if (loadingView.getParent() == null)
                    getRootViewGroup().addView(loadingView);
                loadingView.setVisibility(View.VISIBLE);
                loadingView.showLoading();
            }
        });

    }

    public void hideLoading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loadingView != null) {
                    loadingView.dismissLoading();
                    loadingView.setVisibility(View.GONE);
                    getRootViewGroup().removeView(loadingView);
                }
            }
        });

    }

    public void showTips(final String tips) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (tipsView == null) {
                    tipsView = new TextView(HallBaseActivity.this);
                    tipsView.setTextSize(CoocaaApplication.Dpi(36));
                    tipsView.setTextColor(Color.WHITE);
                    tipsView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
                }
                getRootViewGroup().addView(tipsView);
                tipsView.setText(tips);
                tipsView.setVisibility(View.VISIBLE);
            }
        });
    }

    public void hideTips() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (tipsView != null) {
                    tipsView.setVisibility(View.GONE);
                    getRootViewGroup().removeView(tipsView);
                }
            }
        });
    }

    private ViewGroup getRootViewGroup() {
        return (ViewGroup) ((ViewGroup) findViewById(android.R.id.content))
                .getChildAt(0);
    }

    @Override
    protected void onActivityStackExit() {
        bInitListener = false;
        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                try {
                    XServiceManager.getLitePMService().removeInstallListener(installListener);
                    downloader.removeListener(downloaderListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        super.onActivityStackExit();
    }

    private ILitePMInstallListener.Stub installListener = new ILitePMInstallListener.Stub() {
        @Override
        public void onInstallStart(String apkfile, AppInfo pkgname, final InstallParams params) throws RemoteException {

        }

        @Override
        public void onInstallEnd(final String apkfile, final AppInfo appInfo, final int result, final String extra, final InstallParams params) throws RemoteException {
            if (result == 0) {
//                Bitmap bitmap = null;
//                try {
//                    PackageInfo info = getPackageManager().getPackageInfo(appInfo.pkgName, 0);
//                    bitmap = ((BitmapDrawable) info.applicationInfo.loadIcon(getPackageManager())).getBitmap();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                final Bitmap _bitmap = bitmap;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Bitmap bitmap = _bitmap;
                        String tipStr = getResources()
                                .getString(R.string.toast_install_success);
                        // 弱提示 应用安装完成
//                        if (bitmap != null)
//                            TipToast.getInstance().showToast(bitmap, tipStr);
//                        else
                        TipToast.getInstance().showToast(tipStr);
                    }
                });
            }
            if (CoocaaApplication.isRoot()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result != 0) {
                            if (extra != null) {
                                if (extra.contains("INSTALL_FAILED_INSUFFICIENT_STORAGE")) {
                                    TipToast.getInstance().showToast(
                                            mContext.getResources().getString(
                                                    R.string.toast_install_failed_nospc));
                                } else if (extra.contains("nosdcard")) {
                                    TipToast.getInstance().showToast(
                                            mContext.getResources().getString(
                                                    R.string.toast_install_failed_nosdcard));
                                } else if (extra.contains("INSTALL_FAILED_INVALID_APK")) {
                                    TipToast.getInstance()
                                            .showToast(
                                                    mContext.getResources().getString(
                                                            R.string.toast_install_failed_invalid_apk));
                                } else {
                                    TipToast.getInstance().showToast(
                                            mContext.getResources().getString(
                                                    R.string.toast_install_failed));
                                }
                            }
                        }
                    }
                });
            }
        }
    };

    private ILiteDownloadServiceListener.Stub downloaderListener = new ILiteDownloadServiceListener.Stub() {
        @Override
        public void onStarted(DownloadTask task) throws RemoteException {

        }

        @Override
        public void onPaused(DownloadTask task) throws RemoteException {

        }

        @Override
        public void onCanceled(DownloadTask task) throws RemoteException {

        }

        @Override
        public void onProgressUpdate(DownloadTask task, int percent, long fileSize, long downloadedSize) throws RemoteException {

        }

        @Override
        public void onSuccess(DownloadTask task) throws RemoteException {

        }

        @Override
        public void onError(DownloadTask task, int err_code, String err_msg) throws RemoteException {
            if (err_code == -ErrorCode.EC_LITEDOWNLOADER_NO_SPACE_LEFT) {
                //空间不足
                LiteHandlerThread.postOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TipToast.getInstance().showToast(mContext.getResources().getString(R.string.toast_download_error_nospc));
                    }
                });
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        appDuring = configSharePreference.getLong(getConfigName(APP_DURING), 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        launchApp = false;
    }

    protected void logStart() {
        logEnd();
        long start = System.currentTimeMillis();
        if (start <= 0)
            return;
        LogAPIForAppStore.centerStart(hallName, start);
        LogUtils.d("hall_log", "commint start " + hallName + " time start " + start);
        saveTime(getConfigName(START_TIME), start);
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (launchApp) {
                    appDuring += 1000;
                    saveTime(getConfigName(APP_DURING), appDuring);
                    LogUtils.d("hall_log", "app during is " + appDuring);
                }
                saveTime(getConfigName(END_TIME), System.currentTimeMillis());
            }
        };
        if (log == null)
            log = new Timer();
        log.schedule(task, 1000, 1000);
    }

    protected void logEnd() {
        if (log != null)
            log.cancel();
        long end = configSharePreference.getLong(getConfigName(END_TIME), 0);
        if (end > 0) {
            long start = configSharePreference.getLong(getConfigName(START_TIME), 0);
            long during = configSharePreference.getLong(getConfigName(APP_DURING), 0);
            if (start > 0 && during >= 0 && (end - start - during) > 0) {
                LogAPIForAppStore.centerStop(hallName, start, end, (int) (end - start - during));
                LogUtils.d("hall_log", "commint stop " + hallName + " time start " + start + " end " + end + " during " + during);
            }
            saveTime(getConfigName(END_TIME), 0);
            saveTime(getConfigName(APP_DURING), 0);
        }
        log = null;
    }

    protected void cancelLogTask() {
        if (log != null)
            log.cancel();
    }

    public static void logStartApp(String pkgName) {
        HallBaseActivity.launchApp = true;
        String name = Android.getAppNameByPkg(pkgName);
        LogUtils.d("hall_log", "commit startapp title " + name + " pkg " + pkgName);
        LogAPIForAppStore.centerAppStart(hallName, name, pkgName, System.currentTimeMillis());
    }

    private void saveTime(String key, long time) {
        SharedPreferences.Editor editor = configSharePreference.edit();
        editor.putLong(key, time);
        editor.commit();
    }

    protected String getConfigName(String name) {
        return hallName + "_" + name;
    }


    private static final String APP_SESSION_KEY = "5582a8c967e58e7084000962";

    @Override
    protected String getAppSessionKey() {
        return APP_SESSION_KEY;
    }
}
